const LOGIN_OF_OK = 1; // 表示登陆成功
const LOGIN_PWD_OF_FALSE = 2; // 表示密码有误
const USER_OF_UNDEFINED = 3; // 表示未注册用户
const REG_OF_OK = 4; // 表示注册成功
const REG_USER_OF_EXIST = 5; // 表示用户已被注册
const LOGIN_STATE_OF_FALSE = false; // 表示非登陆状态
const LOGIN_STATE_OF_TRUE = true; // 表示登陆状态

// 判断是否为pc端
function IsPC(){  
  var userAgentInfo = navigator.userAgent;
  var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");  
  var flag = true;  
  for (var v = 0; v < Agents.length; v++) {  
      if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }  
  }  
  return flag;  
}


// 个String添加去空格属性方法
String.prototype.trim = function(){
　　return this.replace(/(^\s*)|(\s*$)/g, "");
}

// 提示框
function tooltip(targetEl, obj = {}) {
  let tooltipBox = document.createElement("div");
  tooltipBox.classList.add("tooltip");
  tooltipBox.innerText = obj.message;
  targetEl.appendChild(tooltipBox);
  setTimeout(() => {
    targetEl.removeChild(
      targetEl.querySelector(".tooltip")
    )
  }, 2000)
}


function initStyle(e) {
  e.classList.remove("wamming")
}

// 使用localStorage存储，实现注册
function regStorage(obj) {
  let user = JSON.parse(localStorage.getItem("user")) || [];
  if (user.length === 0) {
    user.push(obj);
    localStorage.setItem("user", JSON.stringify(user));
    return REG_OF_OK
  } 
  
  let isExist = [];
  isExist = user.filter(it => it.username === obj.username);
  if (isExist.length === 0) {
    user.push(obj);
    localStorage.setItem("user", JSON.stringify(user));
    return REG_OF_OK
  }
  return REG_USER_OF_EXIST 
}

// 根据localStorage存储的内容，实现登陆
function loginStorage(obj) {
  let user = JSON.parse(localStorage.getItem("user")) || [];
  if (user.length === 0) {
    return USER_OF_UNDEFINED
  } 
  
  let isExist = "";
  isExist = user.filter(it => it.username === obj.username)[0];
  if (isExist !== "") {
    if (isExist.password === obj.password) {
      return LOGIN_OF_OK
    }
    return LOGIN_PWD_OF_FALSE
  }
  return USER_OF_UNDEFINED
}

// 判断是否登陆，使用sessionStorage，保存登陆状态
function isLogin() {
  let userSession = sessionStorage.getItem("user_session") || "";
  if (userSession === "") {
    return LOGIN_STATE_OF_FALSE
  }
  return LOGIN_STATE_OF_TRUE 
}


// 创建WebSql本地数据库
var db = openDatabase("game_record", "", "my DB", 1024 * 100);
// 数据库查找
function select(getdata) {
  db.transaction(tx => {
    tx.executeSql("SELECT * FROM my_data_table", [], function (tx, rs) {
      getdata && getdata(rs)
    }, null);
 })
}
// 数据库插入
function insert(data) {
  db.transaction(tx => {
    tx.executeSql("CREATE TABLE IF NOT EXISTS my_data_table(username TEXT, score TEXT, ctime INTEGER)");
    tx.executeSql("INSERT INTO my_data_table VALUES (?,?,?)", [data.username, data.score, data.ctime], (tx, res) => {
      console.log('ok')
    })
  })
}

// 退出登陆状态
function quitToLogin() {
  sessionStorage.removeItem("user_session");
  window.location.href = "login.html"
}